package rwlivbk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import rwlivbk.model.DanmuMessage;
import rwlivbk.utils.JwtTokenUtil;

@CrossOrigin
@RestController
public class DanmuController {

    private final RedisTemplate<String, DanmuMessage> redisTemplate;
    private final JwtTokenUtil jwtTokenUtil;

    @Autowired
    public DanmuController(RedisTemplate<String, DanmuMessage> redisTemplate, JwtTokenUtil jwtTokenUtil) {
        this.redisTemplate = redisTemplate;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @MessageMapping("/sendDanmu")
    @SendTo("/topic/danmu")
    public void sendDanmu(DanmuMessage danmuMessage, StompHeaderAccessor headerAccessor) {
        String authHeader = headerAccessor.getFirstNativeHeader("Authorization");

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new IllegalArgumentException("Invalid Authorization header.");
        }

        // 从 Authorization 头部提取 token
        String token = authHeader.substring(7);

        // 从 token 中提取用户名
        String username = jwtTokenUtil.getUsernameFromToken(token);

        // 设置弹幕消息的用户名
        danmuMessage.setUsername(username);
        System.out.println("Received danmu: " + danmuMessage);

        // 将弹幕消息存储到 Redis 中，用于实时获取
        redisTemplate.opsForList().leftPush("danmuList", danmuMessage);
    }
}
